package cn.wolfcode.luowowo.website.interceptor;

import cn.wolfcode.luowowo.cache.prefix.UserInfoKeyPrefix;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截校验
 * <p>
 * 继承: extends HandlerInterceptorAdapter
 * <p>
 * 实现接口:  HandlerInterceptor
 * <p>
 * HandlerInterceptorAdapter  适配器模式
 * JDK 1.8以前接口没有显示,一些非关注方法也需要重写,JDK 1.8 之后引入默认实现这种说法
 * 实现接口时,选用需要关注方法实现即可
 */
public class CheckLoginInterceptor implements HandlerInterceptor {

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //登录校验
        Cookie c = CookieUtil.getCookie(request, UserInfoKeyPrefix.USER_LOGIN_COOKIE_NAME);
        UserInfo userInfo = null;

        if (c != null) {
            userInfo=userInfoRedisService.getUserInfo(c.getValue());
        }
        //动态请求处理
        //HandlerMethod  :  请求映射方法在springmvc中的封装对象
        //而静态资源处理使用的是另外一种处理对象
        if (handler instanceof HandlerMethod) {

            //判断当前登录请求方法上面是有贴有@RequireLogin登录拦截
            HandlerMethod hm = (HandlerMethod) handler;
            if (hm.hasMethodAnnotation(RequireLogin.class)) {

                if (userInfo == null) {
                    response.sendRedirect("/login.html");
                    return false;
                }
            }
        }
        return true;
    }
}
